import {takeEvery, select, call, put} from 'redux-saga/effects'
import axios from 'axios'

// 引入常量
import {DOLOGINSAGA, DOLOGINEMAILSAGA} from '../constants'
import {DoLogin} from '../actions/login'
import {IsUserLogin} from '../actions/popup'
import {GetUserBaseInfo} from '../actions/userinfo'
import { API_URL } from '../../env'

// 发送请求到后端,判断用户账号密码是否正确
function* doLoginSaga(action) {
    // select 为获取全局数据
    // const user = yield select(state => state.PublicReducer)
    const res = yield call(axios.post, API_URL + "login/account", {...action.data})
    if (res.data.data === 'success') {
        // 记录用户名和用户密码
        let obj = {activate:false, spinning: false, ...action.data}
        yield put(DoLogin(obj))
        // 记录用户状态
        let obj1 = {isLogin:true}
        yield put(IsUserLogin(obj1))
        // 请求并记录用户基本信息
        yield put(GetUserBaseInfo(res.data.baseUserInfo))
        const user = yield select(state => state.PublicReducer)
        console.log("user is", user)

    } else if (res.data.data === 'no username') {
        let obj = {spinning: false, login_user_error:true, login_passwd_error:false}
        yield put(DoLogin(obj))
    } else if(res.data.data === 'fail passwd') {
        let obj = {spinning: false, login_user_error:false, login_passwd_error:true}
        yield put(DoLogin(obj))
    }
}

// 发送请求到后端,判断用户邮箱账号密码是否正确
function* doLoginEmailSaga(action) {
    const res = yield call(axios.post, API_URL + "login/email_account", {...action.data})
    if (res.data.data === 'success') {
        // 记录用户邮箱和用户密码
        let obj = {activate:false, spinning: false, ...action.data}
        yield put(DoLogin(obj))
        // 记录用户状态
        let obj1 = {isLogin:true}
        yield put(IsUserLogin(obj1))
        // 请求并记录用户基本信息(不包括任务信息)
        yield put(GetUserBaseInfo(res.data.baseUserInfo))
    } else if (res.data.data === 'no email') {
        let obj = {spinning: false, login_email_error:true, login_passwd_error:false}
        yield put(DoLogin(obj))
    } else if(res.data.data === 'fail passwd') {
        let obj = {spinning: false, login_email_error:false, login_passwd_error:true}
        yield put(DoLogin(obj))
    }
}

export function* loginSaga () {
    yield takeEvery(DOLOGINSAGA, doLoginSaga)
    yield takeEvery(DOLOGINEMAILSAGA, doLoginEmailSaga)
}